package com.wtf.handler;

import com.wtf.config.SpringContextUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.rpc.pojo.RpcRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 11/10/2020
 */
@Component
public class UserChannelHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private SpringContextUtils springContextUtils;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String className = ((RpcRequest) msg).getClassName();
        Class<?> aClass = Class.forName(className);
        Object bean = springContextUtils.getBean(aClass);
        if (bean == null) {
            throw new ClassNotFoundException("Class " + aClass + " not found.");
        }
        Class<?> beanClass = bean.getClass();

        Class<?>[] parameterTypes = ((RpcRequest) msg).getParameterTypes();
        String methodName = ((RpcRequest) msg).getMethodName();
        Method method = beanClass.getDeclaredMethod(methodName, parameterTypes);

        Object[] parameters = ((RpcRequest) msg).getParameters();
        Object result = method.invoke(bean, parameters);
        System.out.println("result is:" + result.toString());

        ctx.writeAndFlush(result);
    }
}
